1. 随机小数

  • random.random() -> 随机生成大于0且小于1之间的小数

import random

r = random.random()  # 0.7803644545870692

  • random.uniform(x, y) -> 随机生成大于等于 x 且小于 y 的小数

import random

ur = random.uniform(1, 3)  # 2.1193483830769067

2. 随机整数

  • random.randint(x, y) -> 随机生成大于 x 且小于等于 y 的整数

import random

r_int = random.randint(1, 5)  # 3

  • random.randrange(x, y, s) -> s 步长(和切片中的步长一样)-> 随机生成大于 x 且小 y 的整数

import random

r_int = random.randrange(1, 10, 2)  # 5 -> 随机生成大于等于 1 且小于 10 之间的奇数

3. 随机选择返回

  • random.choice(seq) -> seq: 列表/元组/字符串 -> 随机选择一个返回

import random

lis = [1, 3, ['一', '二']]
r_c = random.choice(lis)  # ['一', '二']

  • random.sample(seq, num) -> seq: 列表/元组/字符串 num: 返回多少个 -> 随机选择多个返回

import random

lis = [1, 3, ['一', '二'], 'a', 'b']
r_c = random.sample(lis, 2)  # [['一', '二'], 'a']

4. 打乱列表的顺序

  • random.shuffle(列表) 

import random

lis = [1, 2, 3, 4, 5, 6]
random.shuffle(lis)
print(lis)  # [3, 4, 6, 1, 2, 5]